<template>
  <div class="websocket-notification">
    <el-popover
      placement="bottom"
      width="350"
      trigger="click"
      @show="handleShow"
    >
      <div class="notification-container">
        <div class="notification-header">
          <div class="title">
            <i class="el-icon-bell"></i>
            <span>消息通知</span>
            <el-badge :value="unreadCount" :max="99" class="badge" v-if="unreadCount > 0" />
          </div>
          <div class="actions">
            <el-button type="text" size="mini" @click="markAllAsRead">全部已读</el-button>
            <el-button type="text" size="mini" @click="clearAll">清空</el-button>
          </div>
        </div>
        <el-divider></el-divider>
        <div class="notification-content" v-loading="loading">
          <div v-if="notifications.length === 0" class="empty-state">
            <i class="el-icon-message"></i>
            <p>暂无通知</p>
          </div>
          <el-scrollbar style="height: 300px" v-else>
            <div
              v-for="notification in notifications"
              :key="notification.id"
              class="notification-item"
              :class="{ 'is-read': notification.read }"
              @click="handleNotificationClick(notification)"
            >
              <div class="notification-icon">
                <i :class="getNotificationIcon(notification.type)"></i>
              </div>
              <div class="notification-body">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-message">{{ notification.message }}</div>
                <div class="notification-time">{{ formatTime(notification.timestamp) }}</div>
              </div>
              <div class="notification-actions">
                <el-button
                  type="text"
                  size="mini"
                  @click.stop="markAsRead(notification)"
                  v-if="!notification.read"
                >
                  标为已读
                </el-button>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
      <el-badge :value="unreadCount" :max="99" :hidden="unreadCount === 0" slot="reference">
        <el-button type="text" class="notification-button">
          <i class="el-icon-bell"></i>
        </el-button>
      </el-badge>
    </el-popover>
    
    <!-- WebSocket连接状态指示器 -->
    <div class="ws-status-indicator" :class="wsStatusClass" :title="wsStatusText"></div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { parseTime } from '@/utils/ruoyi'

export default {
  name: 'WebSocketNotification',
  data() {
    return {
      loading: false
    }
  },
  computed: {
    ...mapGetters([
      'wsStatus',
      'wsConnected',
      'wsNotifications',
      'wsUnreadCount'
    ]),
    notifications() {
      return this.wsNotifications || []
    },
    unreadCount() {
      return this.wsUnreadCount || 0
    },
    wsStatusClass() {
      const statusMap = {
        'connecting': 'connecting',
        'open': 'connected',
        'closed': 'disconnected',
        'error': 'error'
      }
      return statusMap[this.wsStatus] || 'disconnected'
    },
    wsStatusText() {
      const statusMap = {
        'connecting': 'WebSocket 正在连接...',
        'open': 'WebSocket 已连接',
        'closed': 'WebSocket 已断开',
        'error': 'WebSocket 连接错误'
      }
      return statusMap[this.wsStatus] || 'WebSocket 未连接'
    }
  },
  methods: {
    handleShow() {
      // 可以在这里加载更多通知
    },
    markAsRead(notification) {
      this.$wsMarkRead(notification.id)
    },
    markAllAsRead() {
      this.notifications.forEach(notification => {
        if (!notification.read) {
          this.$wsMarkRead(notification.id)
        }
      })
    },
    clearAll() {
      this.$confirm('确认清空所有通知吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$wsClearNotifications()
        this.$message({
          type: 'success',
          message: '已清空所有通知'
        })
      }).catch(() => {})
    },
    handleNotificationClick(notification) {
      // 标记为已读
      if (!notification.read) {
        this.markAsRead(notification)
      }
      
      // 处理通知点击事件
      if (notification.url) {
        // 如果有URL，可以跳转
        this.$router.push(notification.url)
      }
      
      // 触发点击事件，让父组件可以处理
      this.$emit('notification-click', notification)
    },
    getNotificationIcon(type) {
      const iconMap = {
        'info': 'el-icon-info',
        'success': 'el-icon-success',
        'warning': 'el-icon-warning',
        'error': 'el-icon-error',
        'system': 'el-icon-s-platform',
        'message': 'el-icon-message',
        'order': 'el-icon-s-order'
      }
      return iconMap[type] || 'el-icon-bell'
    },
    formatTime(timestamp) {
      if (!timestamp) return ''
      
      const now = new Date().getTime()
      const diff = now - timestamp
      
      // 小于1分钟
      if (diff < 60 * 1000) {
        return '刚刚'
      }
      // 小于1小时
      else if (diff < 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 1000)) + '分钟前'
      }
      // 小于24小时
      else if (diff < 24 * 60 * 60 * 1000) {
        return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
      }
      // 其他情况使用parseTime格式化
      else {
        return parseTime(new Date(timestamp), '{y}-{m}-{d} {h}:{i}')
      }
    },
    // 连接WebSocket
    connectWebSocket() {
      const wsUrl = process.env.VUE_APP_WEBSOCKET_URL
      if (wsUrl && this.wsStatus !== 'open' && this.wsStatus !== 'connecting') {
        this.$wsConnect(wsUrl)
      }
    }
  },
  mounted() {
    // 监听WebSocket消息
    this.$wsOn('message', (data) => {
      // 如果是通知类型的消息，添加到通知列表
      if (data.type === 'notification' || data.notification) {
        const notification = data.notification || data
        this.$wsNotify({
          title: notification.title || '系统通知',
          message: notification.message || notification.content || '您有一条新消息',
          type: notification.type || 'info',
          url: notification.url,
          data: notification.data
        })
      }
    })
    
    // 可以在组件挂载时连接WebSocket
    // this.connectWebSocket()
  }
}
</script>

<style lang="scss" scoped>
.websocket-notification {
  display: flex;
  align-items: center;
  
  .notification-button {
    font-size: 18px;
    padding: 0;
    color: #606266;
    
    &:hover {
      color: #409EFF;
    }
  }
  
  .notification-container {
    .notification-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px;
      
      .title {
        font-size: 16px;
        font-weight: bold;
        display: flex;
        align-items: center;
        
        i {
          margin-right: 5px;
        }
        
        .badge {
          margin-left: 5px;
        }
      }
      
      .actions {
        .el-button {
          margin-left: 10px;
          padding: 0;
        }
      }
    }
    
    .notification-content {
      min-height: 100px;
      
      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 200px;
        color: #909399;
        
        i {
          font-size: 48px;
          margin-bottom: 10px;
        }
      }
      
      .notification-item {
        display: flex;
        padding: 10px;
        border-bottom: 1px solid #EBEEF5;
        cursor: pointer;
        
        &:hover {
          background-color: #F5F7FA;
        }
        
        &.is-read {
          opacity: 0.7;
        }
        
        .notification-icon {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background-color: #F2F6FC;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 10px;
          
          i {
            font-size: 18px;
            color: #409EFF;
          }
        }
        
        .notification-body {
          flex: 1;
          
          .notification-title {
            font-weight: bold;
            margin-bottom: 5px;
          }
          
          .notification-message {
            font-size: 13px;
            color: #606266;
            margin-bottom: 5px;
            word-break: break-word;
          }
          
          .notification-time {
            font-size: 12px;
            color: #909399;
          }
        }
        
        .notification-actions {
          display: flex;
          align-items: flex-start;
          
          .el-button {
            padding: 0;
            margin: 0;
          }
        }
      }
    }
  }
  
  .ws-status-indicator {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-left: 5px;
    
    &.connected {
      background-color: #67C23A;
    }
    
    &.connecting {
      background-color: #E6A23C;
      animation: blink 1s infinite;
    }
    
    &.disconnected {
      background-color: #909399;
    }
    
    &.error {
      background-color: #F56C6C;
    }
  }
}

@keyframes blink {
  0% { opacity: 0.3; }
  50% { opacity: 1; }
  100% { opacity: 0.3; }
}
</style> 